package com.jiangsong.batch;

import com.jiangsong.mapper.ProductMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.partition.support.Partitioner;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ProductPartitioner implements Partitioner {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Map<String, ExecutionContext> partition(int gridSize) {
        Map<String, ExecutionContext> map = new HashMap<>();
        System.out.println("分片器初始化开始");
        int count = productMapper.count();
        int maxExecuteNum = Integer.min(gridSize, count);
        log.info("分片器初始化,i:{},count:{},maxExecute:{}", gridSize, count, maxExecuteNum);
//        System.out.println("分片器初始化,count:" + maxExecuteNum);

        for (int j = 1; j <= maxExecuteNum; j++) {
            ExecutionContext executionContext = new ExecutionContext();
            executionContext.put("jobZoneNo", String.valueOf(j));
            map.put("product_partition" + j, executionContext);
        }
        System.out.println("分片器初始化完成,map" + map);
        return map;
    }
}
